<template>
  <div>
    <el-dialog
      :title="$t('product.productType.createProductMenu')"
      :visible.sync="dialogVisible"
      width="550px"
    >
      <el-input v-model="keyword" @input="searchDirectory" @keyup.enter.native="searchDirectory" :placeholder="$t('product.productType.placeholder.productMenuSearch')">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-tree
        :data='list'
        v-loading='loading'
        v-if="list.length"
        :draggable='!onlyAdd && !searched'
        :props="treeProps"
        node-key="id"
        :render-content="renderContent"
        @node-drop='nodeDrop'
      ></el-tree>
      <div v-else v-loading='loading' class="empty-wrapper">
        <img :src="noDataImage">
        <p v-show="!keyword">{{ $t('product.productType.tips.tip7') }}<span @click="openDialog({id:null,name:'',type:'createTop'})">{{ $t('product.productType.btns.btn6') }}</span></p>
        <p v-show="keyword">{{ $t('common.base.tip.noData') }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <span class="warning-text">*{{ $t('product.productType.tips.tip8') }}</span>
        <el-button @click="dialogVisible = false">{{ $t('common.base.close') }}</el-button>
        <el-button
          class="create-btn"
          type="primary"
          v-track="$track.formatParams('CREATE_NEW_LEVEL1_DIRECTORY')"
          @click="openDialog({id:null,name:'',type:'createTop'})">
          {{ $t('product.productType.btns.btn7') }}
        </el-button>
      </span>
    </el-dialog>

    <edit-directory-dialog ref="editDirDialog" @success='editSuc'></edit-directory-dialog>
  </div>
</template>

<script>
import _ from 'lodash';
import editDirectoryDialog from './editDirectoryDialog';
import {
  getTreeList,
  delTreeList,
  sortTreeList
} from '@src/api/ProductV2Api';
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
export default {
  name:'directory-dialog',
  data(){
    return{
      noDataImage,
      dialogVisible:false,
      keyword:'',
      initList:[],
      list:[],
      flatList:[],  // 拉平的目录树
      treeProps:{
        label:'name',
        children:'tasks'
      },
      propsList:[],
      loading:true,
      delIds:[],
      searched:false
    }
  },
  props:{
    onlyAdd:{
      type:Boolean,
      default:false
    }
  },
  methods:{
    // 搜索
    searchDirectory:_.debounce(function(){
      this.search();
    },400),
    // 新增或编辑成功
    editSuc(parentIds){
      if(this.onlyAdd){
        this.dialogVisible=false;
        this.$emit('addSuc',parentIds);
      }else{
        this.getTreeList();
      }
    },
    // 获取目录树
    async getTreeList(){
      try{
        this.loading=true;
        let {code,result,message}=await getTreeList({conData:0});
        if(code===0){
          this.deleteEmpty(result);
          this.list=result;
          this.initList=result;
          this.flatList=[];
          this.flat(_.cloneDeep(result),this.flatList);
          this.flatList.forEach(item=>{
            delete item.tasks;
          });
        }else{
          this.$notify.error({
            title: this.$t('common.base.requestError'),
            message,
            duration: 2000,
          });
        }
        this.$nextTick(()=>{
          this.loading=false;
        })
      }catch(err){
        console.error(err);
      }
    },
    // 拉平目录树
    flat(tasks,arr){
      tasks.forEach(item=>{
        arr.push(item);
        if(item.tasks && item.tasks.length){
          this.flat(item.tasks,arr);
        }
      });
    },
    deleteEmpty(list){
      list.forEach(item=>{
        item.show=false;
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    open(){
      this.keyword='';
      this.dialogVisible=true;
      this.delIds=[];
      this.getTreeList();
    },
    openDialog(propsData){
      const type=propsData.type;
      if(type==='createTop'){
        propsData.list=this.initList;
      }else{
        this.getList(propsData.id,this.initList,type);
        propsData.list=this.propsList;
      }
      this.$refs.editDirDialog.open(propsData);
    },
    // 获取同级，为了校验名称是否相同
    getList(id,list,type){
      for(let i=0;i<list.length;i++){
        const item=list[i];
        if(id===item.id){
          if(type==='edit') this.propsList=list;
          else this.propsList=item.tasks || []
        }
        if(item.tasks && item.tasks.length) this.getList(id,item.tasks);
      }
    },
    // 删除弹框
    del(id){
      const h=this.$createElement;
      this.$msgbox({
        title: this.$t('common.base.delete'),
        message:h('div',null,[
          h('p',{style:'font-size:16px;'}, this.$t('product.productType.tips.tip9')),
        ]),
        showCancelButton: true,
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        beforeClose:(action,instance,done)=>{
          if(action==='confirm') this.delDirectory(id);
          done();
        }
      })
    },
    // 删除
    async delDirectory(id){
      try{
        let {code,message}=await delTreeList({ids:[id]});
        if(code===0){
          this.getTreeList();
        }else{
          this.$notify.error({
            title: this.$t('common.base.requestError'),
            message,
            duration: 2000,
          });
        }
      }catch(err){
        console.error(err);
      }
    },
    search(){
      const keyword=this.keyword;
      if(keyword){
        this.list=[];
        this.flatList.forEach(item=>{
          if(item.name.indexOf(this.keyword)>-1){
            this.list.push(item);
          }
        });
        this.searched=true;
      }else{
        this.list=[...this.initList];
        this.searched=false;
      }
    },
    // 拖拽完成
    nodeDrop(draggingNode, dropNode, type){
      let params={
        id:draggingNode.data.id
      };
      if(type==='inner'){
        params.parentId=dropNode.data.id;
        params.orderId=dropNode.data.tasks.length-1;
      }else{
        const parentData=dropNode.parent.data;
        if(Array.isArray(parentData)){
          params.parentId='';
          params.orderId=parentData.findIndex(item=>item.id===draggingNode.data.id);
        }else{
          params.parentId=parentData.id;
          params.orderId=parentData.tasks.findIndex(item=>item.id===draggingNode.data.id);
        }
      }
      this.sortTreeList(params);
    },
    // 移动树
    async sortTreeList(params){
      try{
        let {code,message}=await sortTreeList(params);
        if(code!==0){
          this.$notify.error({
            title: this.$t('common.base.requestError'),
            message,
            duration: 2000,
          });
        }
        this.getTreeList();
      }catch(err){
        console.error(err);
      }
    },
    renderContent(h, {node, data, store}){
      const attrs={
        on:{
          mouseenter:()=>{
            data.show=true;
          },
          mouseleave:()=>{
            data.show=false;
          }
        }
      }
      return (
        <span class='directory-tree-node' {...attrs}>
          <el-tooltip effect='dark' content={node.label} placement="top">
            <span class='tree-node-text'>{node.label}</span>
          </el-tooltip>
          <span v-show={data.show} class='class-icon'>
            <el-tooltip effect='dark' content={this.$t('common.base.edit')} placement="top" v-show={!this.onlyAdd}>
              <i class='iconfont icon-bianji' onClick={this.openDialog.bind(this,{id:data.id,name:data.name,type:'edit'})}></i>
            </el-tooltip>
            <el-tooltip effect='dark' content={this.$t('common.base.delete')} placement="top" v-show={!this.onlyAdd}>
              <i class='iconfont icon-zxh' onClick={this.del.bind(this,data.id)}></i>
            </el-tooltip>
            <el-tooltip effect='dark' content={this.$t('product.productType.btns.btn8')} placement="top">
              <i class='iconfont icon-add2' onClick={this.openDialog.bind(this,{id:data.id,name:'',type:'create'})}></i>
            </el-tooltip>
            <i class='iconfont icon-tuozhuaipaixu' v-show={!this.onlyAdd}></i>
          </span>
        </span>
      )
    }
  },
  components:{
    [editDirectoryDialog.name]:editDirectoryDialog
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body{
  padding: 10px 20px 0;
}

.create-btn{
  float: left;
}
::v-deep .class-icon{
  display: inline-block;
  margin-left: 12px;
  .iconfont{
    font-size: 12px;
    color:$text-color-secondary;
    margin-left: 4px;
  }
}
.el-tree{
  margin-top: 12px;
  max-height: 350px;
  min-height: 250px;
  overflow-y: auto;
}
::v-deep .directory-tree-node{
  display: inline-block;
  width: 100%;
  .tree-node-text{
    display: inline-block;
    max-width: calc(100% - 110px);
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    transform: translateY(4px);
  }
}
.empty-wrapper{
  img{
    display: block;
    width: 160px;
    margin: 30px auto 8px;
  }
  p{
    text-align: center;
    color: $text-color-regular;
    span{
      cursor: pointer;
      color: $color-main;
    }
  }
}
.warning-text{
  margin: 10px 0 0;
  color: $color-warning;
}


::v-deep .el-dialog {
  border-radius: 8px;
  overflow: hidden;
  .el-dialog__header {
    font-size: 16px;
    color: #262626;
    padding: 0 0 0 20px;
    background-color: #fafafa;
    height: 44px;
    line-height: 44px;
    .el-dialog__title {
      font-weight: bold;
    }
    .el-dialog__headerbtn {
      right: 25px;
      font-size: 14px;
      line-height: 1;
      height: 100%;
      top: 0;
    }
    i:before {
      font-family: "iconfont" !important;
      content: "\e72a";
    }
  }
}
::v-deep .el-tree-node__content {
  height: 32px;
}
::v-deep .el-input__prefix {
  width: 32px;
  text-align: center;
  left: 0;
  line-height: 32px;
}
::v-deep .el-dialog__footer {
  padding: 10px;
}
.dialog-footer {
  font-size: 0;
  &>*:not(:first-child) {
    margin-left: 12px;
  }
  .warning-text {
    font-size: 14px;
  }
}
</style>